package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.FreezeUser;
import com.tanhua.model.mongo.UnFreezeUser;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

@DubboService
public class ManageApiImpl implements ManageApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(FreezeUser freezeUser) {
        Criteria criteria = Criteria.where("userId").is(freezeUser.getUserId());
        Query query = Query.query(criteria);
        boolean exists = mongoTemplate.exists(query, FreezeUser.class);
        if (!exists) {
            mongoTemplate.save(freezeUser);
        }
    }

    @Override
    public FreezeUser findByUserId(Long userId) {
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria);
        return mongoTemplate.findOne(query, FreezeUser.class);
    }

    @Override
    public void deleteByUserId(Long userId) {
        Query query = Query.query(Criteria.where("userId").is(userId));
        mongoTemplate.remove(query, FreezeUser.class);
    }

    @Override
    public void saveUnFreezeUser(UnFreezeUser unFreezeUser) {
        Criteria criteria = Criteria.where("userId").is(unFreezeUser.getUserId());
        Query query = Query.query(criteria);
        boolean exists = mongoTemplate.exists(query, UnFreezeUser.class);
        if (!exists) {
            mongoTemplate.save(unFreezeUser);
        }
    }
}
